<template>
  <el-button type="primary" @click="dialogVisible=true">添加用户</el-button>

  <!-- 添加或者修改用户弹出框 -->
  <el-dialog
      v-model="dialogVisible"
      :title="isAdd?'添加':'修改'"
      width="30%"
      :before-close="handleClose">
    <el-form ref="formRef"
             :model="userFrom"
             :rules="rules"
             label-width="80px">
      <el-form-item label="昵称" prop="userNickName">
        <el-input v-model="userFrom.userNickName" type="text" maxlength="12"
                  show-word-limit/>
      </el-form-item>
      <el-form-item label="用户名" prop="userUsername">
        <el-input v-model="userFrom.userUsername" type="text" maxlength="12"
                  show-word-limit/>
      </el-form-item>
      <el-form-item label="密码" prop="userPassword">
        <el-input v-model="userFrom.userPassword" type="password" minlength="6"
                  show-word-limit placeholder="不填写表示不修改密码"/>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userFrom.email" type="text" maxlength="20"
                  show-word-limit/>
      </el-form-item>
      <el-form-item label="签名" prop="signature">
        <el-input v-model="userFrom.signature" type="text" maxlength="100"
                  show-word-limit/>
      </el-form-item>

      <!--  分类的图标  -->
      <el-form-item label="头像" prop="headImg">
        <el-upload
            class="avatar-uploader"
            name="headerImg"
            :auto-upload="true"
            action="/api/user/uploadHeadImg"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
        >
          <img v-if="getUploadImgUrl" :src="getUploadImgUrl" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="超级用户" prop="isSuperuser">
        否
        <el-switch v-model="userFrom.isSuperuser"></el-switch>
        是
      </el-form-item>
      <el-form-item label="锁定登录" prop="isSuperuser">
        否
        <el-switch v-model="userFrom.isLock"></el-switch>
        是
      </el-form-item>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="userOperation">
          保存
        </el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>


  <el-divider direction="vertical"></el-divider>
  <el-input
      v-model="searchText"
      placeholder="搜索分类"
      size="default"
      style="width: 350px"
      clearable
      maxlength="12"
      show-word-limit
      @clear="getAll"
      @keydown.enter="getAll"
  >
    <template #append>
      <el-button @click="getAll">
        <el-icon>
          <Search/>
        </el-icon>
      </el-button>
    </template>
  </el-input>
  <el-divider direction="vertical"></el-divider>
  <el-button :icon="Refresh" :loading="loading" @click="refreshTable">
    <span>刷新</span>
  </el-button>
  <el-divider direction="vertical"></el-divider>
  <el-button :loading="loading" type="danger" :disabled="DeleteManyDisable" @click="deleteMany">
    <span>批量删除</span>
  </el-button>

  <el-divider></el-divider>
  <!--  展示区域  -->


  <el-table border :data="tableData" @selection-change="handleSelectionChange" stripe style="width: 100%">
    <el-table-column type="selection" width="55"/>
    <el-table-column prop="userId" label="Id" width="80" sortable/>
    <el-table-column prop="userUsername" label="用户名" width="200"/>
    <el-table-column prop="userNickName" label="昵称" width="200"/>
    <el-table-column prop="headImg" label="头像" width="100">
      <template #default="scope">
        <el-popover :width="280" placement="right">
          <template #reference>
            <el-avatar shape="square" size="large" :src="scope.row.headImg"
                       style="border: 1px solid #454555"/>
          </template>
          <img :src="scope.row.headImg" style="width: 250px">
        </el-popover>
      </template>
    </el-table-column>
    <el-table-column prop="isUse" label="是否锁定" width="100">
      <template #default="scope">
        <el-switch v-model="scope.row.isLock" @change="updateUser(scope.row)"/>
      </template>
    </el-table-column>
    <el-table-column prop="isUse" label="超级用户" width="100">
      <template #default="scope">
        <el-switch v-model="scope.row.isSuperuser" @change="updateUser(scope.row)"/>
      </template>
    </el-table-column>
    <el-table-column prop="email" label="邮箱" min-width="220"/>
    <el-table-column prop="signature" label="签名" min-width="220"/>

    <el-table-column label="时间" min-width="260">
      <template #default="scope">
        注册时间：{{ scope.row.registerTime }}<br>
        登录时间：{{ scope.row.lastLoginTime }}
      </template>
    </el-table-column>

    <el-table-column fixed="right" label="操作" width="120">
      <template #default="scope">
        <el-link type="danger" @click="deleteUser(scope.row.userId)">
          <el-icon>
            <Delete/>
          </el-icon>
        </el-link>
        <el-divider direction="vertical"></el-divider>
        <el-link type="primary" @click="editUser(scope.row)">
          <el-icon>
            <Edit/>
          </el-icon>
        </el-link>
      </template>
    </el-table-column>
  </el-table>

  <el-divider></el-divider>
  <!--分页-->
  <div style="display: flex;">
    <el-pagination
        v-model:current-page="current"
        v-model:page-size="size"
        :page-sizes="[15, 30, 45, 60]"
        :small="true"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin: auto;"
    />
  </div>
</template>

<script>
import {Refresh, Search} from '@element-plus/icons-vue'
import {ElMessage} from "element-plus";

export default {
  name: "UserManage",
  computed: {
    getUploadImgUrl() {
      if (this.uploadImgUrl) {
        return this.uploadImgUrl
      } else {
        return ""
      }
    },
  },
  data() {
    return {
      Refresh, Search,
      // 上传图片的url
      uploadImgUrl: "",
      loading: false,
      searchText: "",
      dialogVisible: false,
      // false 表示修改标签
      isAdd: true,
      userFrom: {
        userId: null,
        userNickName: "",
        userUsername: "",
        userPassword: "",
        email: "",
        signature: "",
        headImg: "",
        isSuperuser: false,
        isLock: false,
      },
      rules: {
        userNickName: [
          {required: true, message: '请输入昵称', trigger: 'blur'},
          {min: 2, max: 12, message: '昵称长度应该在2-12', trigger: 'blur'},
        ],
        userUsername: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 5, max: 12, message: '用户名长度应该在5-12', trigger: 'blur'},
        ],
        userPassword: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, message: '密码长度应该大于6位', trigger: 'blur'},
        ],
        email: [
          {max: 20, message: '邮箱有效长度应该小于20', trigger: 'blur'},
        ],
        signature: [
          {max: 100, message: '座右铭有效长度应该小于100', trigger: 'blur'},
        ],
      },
      tableData: [],
      total: 0,
      current: 1,
      size: 15,
      DeleteManyDisable: true,
      multipleSelection: []
    }
  },
  created() {
    this.getAll()
  },
  methods: {
    async getAll() {
      let {data: result} = await this.$http.get("/api/user/getAll", {
        params: {
          pageSize: this.size,
          pageNum: this.current,
          searchText: this.searchText
        }
      })
      this.tableData = result.dataMap.page.records
      this.current = result.dataMap.page.current
      this.total = result.dataMap.page.total
      this.size = result.dataMap.page.size
    },
    refreshTable() {
      this.loading = true
      this.getAll()
      this.loading = false
    },
    handleClose() {
      this.$refs.formRef.resetFields()
      this.$data.userFrom = this.$options.data().userFrom
      this.uploadImgUrl = ""
      this.isAdd = true
      this.dialogVisible = false
    },
    async updateUser(item) {
      this.loading = true
      let {data: result} = await this.$http.post("/api/user/updateUser", item)
      if (result.code !== 200) {
        ElMessage.error({
          showClose: true, message: result.msg
        })
      } else {
        ElMessage.success({
          showClose: true, message: result.msg
        })
      }
      this.loading = false
      this.handleClose()
      this.refreshTable()
    },

    userOperation() {
      if (this.isAdd) {
        this.addUser()
      } else {
        this.updateUser(this.userFrom)
      }
    },

    editUser(item) {
      // es6 新特性，深拷贝
      this.userFrom = {...item}
      this.userFrom.userPassword = null
      this.rules.userPassword = [{min: 6, message: '密码长度应该大于6位', trigger: 'blur'},]
      this.uploadImgUrl = item.headImg
      this.isAdd = false
      this.dialogVisible = true
    },
    addUser() {
      this.$refs.formRef.validate(async (validate) => {
        if (validate) {
          let {data: result} = await this.$http.post("/api/user/updateUser", this.userFrom)
          if (result.code === 400) {
            ElMessage.error({
              showClose: true, message: result.msg
            })
          } else {
            ElMessage.success({
              showClose: true, message: result.msg
            })
            this.handleClose()
            this.refreshTable()
          }
        } else {
          ElMessage.error({
            showClose: true, message: "表单填写有误！"
          })
        }
      })
    },


    async deleteUser(userId) {
      this.loading = true
      let {data: result} = await this.$http.get("/api/user/deleteUser", {
        params: {
          userId: userId,
        }
      })
      if (result.code !== 200) {
        ElMessage.error({
          showClose: true, message: result.msg
        })
      } else {
        ElMessage.success({
          showClose: true, message: result.msg
        })
      }
      this.refreshTable()
    },
    // 多选状态改变
    handleSelectionChange(val) {
      if (val.length === 0) {
        // 批量删除不可用
        this.DeleteManyDisable = true
      } else {
        this.DeleteManyDisable = false
      }
      let list = []
      val.forEach((item) => {
        list.push(item.userId)
      })
      this.multipleSelection.value = list
      // console.log(this.multipleSelection.value)
    },
    async deleteMany() {
      this.loading = true
      let {data: result} = await this.$http.post("/api/user/deleteMany", this.multipleSelection.value)
      if (result.code !== 200) {
        ElMessage.error({
          showClose: true, message: result.msg
        })
      } else {
        ElMessage.success({
          showClose: true, message: result.msg
        })
      }
      this.refreshTable()
    },

    // 上传前检查文件格式和大小
    beforeAvatarUpload(rawFile) {
      // console.log(rawFile.type)
      // console.log(typeof rawFile.type)
      // console.log(rawFile.type !== 'image/jpeg')
      let allowTypes = ['image/jpeg', "image/jpg", 'image/png', 'image/webp', 'image/icon'];
      if (!allowTypes.includes(rawFile.type)) {
        ElMessage.error('文件格式不正确!')
        return false
      } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('文件大小不能大于 2MB!')
        return false
      }
      return true
    },
    // 上传成功修改预览
    handleAvatarSuccess(response) {
      // console.log(response)
      let {code, dataMap} = response
      this.uploadImgUrl = dataMap.imgPath
      this.userFrom.headImg = dataMap.imgPath
    },
    // 分页大小改变
    handleSizeChange() {
      this.refreshTable()
    },
    // 分页页数改变
    handleCurrentChange() {
      this.refreshTable()
    },
  }

}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 150px;
  height: 150px;
  display: block;
  /*margin-left: 30px;*/
  border-radius: 20px;
}

.avatar-uploader {
  border: 1px solid #8c939d;
  border-radius: 20px;
  margin-left: 30px;
  height: 150px;
  width: 150px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  display: flex;
}


.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 140px;
  height: 60px;
  align-items: center;
  text-align: center;
}
</style>